import router from './router';
import tokenUtil from '@/utils/tokenUtil';
import { getUserInfo } from '@/services/api/user';
import storeUtil from '@/utils/storeUtil';
import useSetting from '@/store/modules/setting';
import useStore from '@/store/modules/menu';
import useUserStore from '@/store/modules/useUserStore';
import { getSetting } from '@/services/api/setting';
import store from './store';

const setting = useSetting(store);
const menuStore = useStore(store);
const userStore = useUserStore(store);

router.beforeEach(async (to: any, _from: any, next) => {
  to.meta.title && (document.title = to.meta.title);
  if (to.name === 'htmlPage') {
    const { name } = to.params;
    document.title = `${name}`;
  }
  if (tokenUtil.getToken()) {
    if (!userStore.userInfo) {
      getUserInfo().then(res => {
        if (res.data) {
          const userInfoData = res.data;
          userStore.updateUserInfo(userInfoData);
          storeUtil.setInfo('userInfo', userInfoData, 24 * 60 * 60);
        }
      });
    }
  }
  if (!setting.isLoadSetting) {
    getSetting().then(({ data }) => {
      if (data) {
        if (tokenUtil.getToken()) {
          setting.updateIsLoadSetting(true);
          menuStore.updateIsLoadingMenu(true);
        }
        setting.updateFavicon(data.favicon);
        setting.updateTitle(data.title);
        setting.updateLogo(data.logo);
        setting.updateAgreement(data.agreement);
        setting.updateLogins(data.thirdLogin);
        menuStore.updateIndexMenu(data.menus);
      }
    });
  }
  next();
});
